<template>
  <div class="nlp-knowledge-processing">
    <el-card>
      <div slot="header" class="clearfix">
        <span>维修报告处理</span>
      </div>
      <el-upload
        class="upload-demo"
        drag
        :auto-upload="false"
        :before-upload="beforeUpload"
        :on-change="handleFileChange"
        :file-list="fileList"
        :show-file-list="true"
        accept=".doc,.docx,.pdf"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将Word/PDF报告拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          仅支持Word/PDF文件，单个文件不超过10MB
        </div>
      </el-upload>
      <el-button type="primary" style="margin-top: 10px" @click="processFiles">调用NLP引擎生成摘要并提取关键信息</el-button>
      <el-table
        v-if="tempPool.length"
        :data="tempPool"
        style="width: 100%; margin-top: 20px"
        size="small"
        border
      >
        <el-table-column prop="name" label="文件名" width="200" />
        <el-table-column prop="summary" label="NLP摘要" />
        <el-table-column prop="keyInfo" label="关键信息" />
        <el-table-column prop="uploadTime" label="上传时间" width="160" />
      </el-table>
      <div v-else style="margin-top: 20px; color: #888;">知识临时池暂无数据</div>
      <el-button type="danger" size="mini" style="margin-top: 10px" @click="clearTempPool" v-if="tempPool.length">清空知识临时池</el-button>
    </el-card>

    <el-card style="margin-top: 30px">
      <div slot="header" class="clearfix">
        <span>规则自动提取</span>
        <el-button type="success" size="mini" style="float: right" @click="extractRules">规则自动提取</el-button>
      </div>
      <el-table
        v-if="ruleBase.length"
        :data="ruleBase"
        style="width: 100%; margin-top: 10px"
        size="small"
        border
      >
        <el-table-column prop="pattern" label="高频模式/规则" />
        <el-table-column prop="source" label="来源" width="120" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
      </el-table>
      <div v-else style="margin-top: 20px; color: #888;">故障诊断规则库暂无数据</div>
    </el-card>

    <el-card style="margin-top: 30px">
      <div slot="header" class="clearfix">
        <span>规则更新日志</span>
      </div>
      <el-timeline style="margin-top: 10px">
        <el-timeline-item
          v-for="(log, idx) in ruleLogs"
          :key="idx"
          :timestamp="log.time"
          placement="top"
        >
          新增规则：{{ log.pattern }}
        </el-timeline-item>
        <div v-if="!ruleLogs.length" style="color: #888;">暂无规则更新日志</div>
      </el-timeline>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'NLPKnowledgeProcessing',
  data() {
    return {
      fileList: [], // 上传的文件列表
      tempPool: [], // 知识临时池
      ruleBase: [], // 规则库
      ruleLogs: []  // 规则更新日志
    }
  },
  created() {
    this.loadLocalData()
  },
  methods: {
    beforeUpload(file) {
      const isAllowed = file.name.endsWith('.doc') || file.name.endsWith('.docx') || file.name.endsWith('.pdf')
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isAllowed) {
        this.$message.error('仅支持Word/PDF文件')
        return false
      }
      if (!isLt10M) {
        this.$message.error('单个文件不能超过10MB')
        return false
      }
      return true
    },
    handleFileChange(file, fileList) {
      this.fileList = fileList
    },
    processFiles() {
      if (!this.fileList.length) {
        this.$message.warning('请先上传Word/PDF报告')
        return
      }
      // 模拟NLP摘要和关键信息提取
      const now = new Date().toLocaleString()
      const newTemp = this.fileList.map(f => {
        return {
          name: f.name,
          summary: this.mockSummary(f.name),
          keyInfo: this.mockKeyInfo(f.name),
          uploadTime: now
        }
      })
      this.tempPool = [...this.tempPool, ...newTemp]
      this.fileList = []
      this.saveLocalData()
      this.$message.success('NLP摘要与关键信息已生成，已存入知识临时池')
    },
    mockSummary(name) {
      // 简单模拟摘要
      const samples = [
        '故障原因：轴承润滑不足，解决方法：更换润滑脂并清洁轴承',
        '故障原因：电机过热，解决方法：检查冷却系统',
        '故障原因：线路老化，解决方法：更换老化线路',
        '故障原因：振动异常，解决方法：检查并紧固地脚螺栓',
        '故障原因：传感器失灵，解决方法：更换传感器'
      ]
      return samples[Math.floor(Math.random() * samples.length)]
    },
    mockKeyInfo(name) {
      // 简单模拟关键信息
      const keys = [
        '轴承,润滑脂,清洁',
        '电机,过热,冷却',
        '线路,老化,更换',
        '振动,异常,螺栓',
        '传感器,失灵,更换'
      ]
      return keys[Math.floor(Math.random() * keys.length)]
    },
    clearTempPool() {
      this.$confirm('确定要清空知识临时池吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.tempPool = []
        this.saveLocalData()
        this.$message.success('已清空知识临时池')
      })
    },
    extractRules() {
      if (!this.tempPool.length) {
        this.$message.warning('知识临时池暂无数据，无法提取规则')
        return
      }
      // 模拟高频模式提取
      const patterns = [
        { pattern: '振动异常+温度高→轴承故障', source: 'NLP分析' },
        { pattern: '电流波动+噪音大→电机故障', source: 'NLP分析' },
        { pattern: '油温升高+漏油→密封失效', source: 'NLP分析' },
        { pattern: '报警频繁+响应慢→传感器故障', source: 'NLP分析' }
      ]
      // 随机新增1-2条规则
      const now = new Date()
      const updateTime = now.toLocaleString()
      const lastHour = now.getTime() - 60 * 60 * 1000
      // 只保留1小时内的规则
      this.ruleBase = this.ruleBase.filter(r => {
        return new Date(r.updateTime).getTime() > lastHour
      })
      // 随机选取未入库的规则
      const existing = this.ruleBase.map(r => r.pattern)
      const newPatterns = patterns.filter(p => !existing.includes(p.pattern))
      const addCount = Math.floor(Math.random() * 2) + 1
      const toAdd = newPatterns.slice(0, addCount)
      toAdd.forEach(p => {
        this.ruleBase.push({ ...p, updateTime })
        this.ruleLogs.unshift({ pattern: p.pattern, time: updateTime })
      })
      // 只保留最近20条日志
      this.ruleLogs = this.ruleLogs.slice(0, 20)
      this.saveLocalData()
      if (toAdd.length) {
        this.$message.success('已自动提取并更新' + toAdd.length + '条规则')
      } else {
        this.$message.info('暂无新高频模式可提取')
      }
    },
    saveLocalData() {
      localStorage.setItem('nlp_tempPool', JSON.stringify(this.tempPool))
      localStorage.setItem('nlp_ruleBase', JSON.stringify(this.ruleBase))
      localStorage.setItem('nlp_ruleLogs', JSON.stringify(this.ruleLogs))
    },
    loadLocalData() {
      this.tempPool = JSON.parse(localStorage.getItem('nlp_tempPool') || '[]')
      this.ruleBase = JSON.parse(localStorage.getItem('nlp_ruleBase') || '[]')
      this.ruleLogs = JSON.parse(localStorage.getItem('nlp_ruleLogs') || '[]')
    }
  }
}
</script>

<style scoped>
.nlp-knowledge-processing {
  max-width: 900px;
  margin: 0 auto;
  padding: 30px 0;
}
.upload-demo {
  width: 100%;
  margin-bottom: 20px;
}
</style>
